package service

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"go_init/global"
	"go_init/models"
	"go_init/repository"
	"go_init/view"
)

var (
	CacheStudent = "go_cache:student"
)

type HomeService struct {
	HomeRepository *repository.HomeRepository
}

func NewHomeService() *HomeService {
	return &HomeService{
		HomeRepository: repository.NewHomeRepository(),
	}
}

func (h *HomeService) Select() ([]models.Home, error) {
	data, err := global.Redis.Get(CacheStudent)
	if err != nil {
		all, err := h.HomeRepository.FindAll()
		if err != nil {
			return nil, err
		}
		set, err := global.Redis.Set(CacheStudent, all, 1000000)
		if err != nil {
			logrus.Infof("发生错误：%s, %v", err.Error(), set)
		}
		return all, nil
	}
	var result []models.Home
	err = json.Unmarshal(data, &result)
	return result, err
}

func (h *HomeService) Add(params view.HomeAddReq) error {
	return h.HomeRepository.InsertOne(params)
}


